package com.aracky.system.service.impl;

import com.aracky.common.exception.BaseException;
import com.aracky.system.mapper.SysDictTypeMapper;
import com.aracky.system.model.entity.SysDictData;
import com.aracky.system.model.entity.SysDictType;
import com.aracky.system.model.form.SysDictTypeForm;
import com.aracky.system.model.vo.SysDictVO;
import com.aracky.system.service.SysDictTypeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典类型表 服务实现类
 * </p>
 *
 * @author zengzhiping
 * @since 2022-07-15 09:11:41
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {

    @Resource
    private SysDictTypeMapper sysDictTypeMapper;

    @Override
    public SysDictType getDictTypeId(String dictCode) {
        LambdaQueryWrapper<SysDictType> lambdaQueryWrapper = Wrappers.<SysDictType>lambdaQuery()
                .eq(SysDictType::getDictCode, dictCode);
        return sysDictTypeMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public void dictCodeExists(SysDictTypeForm sysDictTypeForm) {
        //1.先判断字典编码是否存在
        LambdaQueryWrapper<SysDictType> lambdaQueryWrapper = Wrappers.<SysDictType>lambdaQuery()
                .eq(SysDictType::getDictCode, sysDictTypeForm.getDictCode())
                .ne(sysDictTypeForm.getDictId() != null, SysDictType::getDictId, sysDictTypeForm.getDictId());
        long count = this.count(lambdaQueryWrapper);
        if (count > 0) {
            throw new BaseException("当前字典编码已存在");
        }
    }

    @Override
    public Map<String, List<SysDictVO>> getMapList(List<String> dictCodeList) {
        Map<String, List<SysDictVO>> resultMap = null;

        List<SysDictVO> mapList = sysDictTypeMapper.findMapList(dictCodeList);

        if (mapList == null || mapList.isEmpty()) {
            return resultMap;
        }
        resultMap = mapList.stream().collect(Collectors.groupingBy(SysDictVO::getCode));

        return resultMap;
    }
}
